package departmentvalidator

import (
	"errors"
	"fmt"
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/dto"
	"yunj/pkg/yunj/app/enum/admin/departmentenum"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/core/builder"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Department struct {
	validate.Validator
}

func (v *Department) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Department) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	datas = util.MapFloat64ToUints(datas)
	builderRaw, exists := datas["builder"]
	if !exists {
		err = errors.New("builder参数缺失")
		return
	}
	formBuilder, ok := builderRaw.(*builder.Form)
	if !ok {
		err = errors.New("builder参数异常")
		return
	}
	loadDepartment, err := builder.FormLoadValue[dto.AdminDepartmentPageFormLoadResponse](formBuilder)
	if err != nil {
		return
	}

	currTime := time.Now().In(time.Local)
	dbDepartment := &model.AdminDepartment{
		Name:      util.MapKeyValue(datas, "name", ""),
		Intro:     util.MapKeyValue(datas, "intro", ""),
		UpdatedAt: &currTime,
	}
	// pid
	var pid uint64
	isAddChild := util.MapKeyValue(datas, "is_add_child", uint8(0)) == 1
	if isAddChild {
		pid = loadDepartment.Pid
	} else {
		if pidRaw, exists := datas["pid"]; exists {
			if pidVal, err := util.ToUint64(pidRaw); err == nil {
				pid = pidVal
			}
		}
	}
	if pid > 0 {
		// 判断是否存在且有效
		var pidExistsCount int64
		if err = global.MySQL.Model(&model.AdminDepartment{}).Where("id = ?", pid).Count(&pidExistsCount).Error; err != nil {
			err = errors.New("父级部门数据异常，请刷新页面后重试")
			return
		}
		dbDepartment.Pid = pid
	}
	// type
	typRaw := util.MapKeyValue(datas, "type", uint8(0))
	typ, ok := departmentenum.TypeEnum.IsValue(typRaw)
	if !ok {
		err = errors.New("类型选择异常异常，请刷新页面后重试")
		return
	}
	dbDepartment.Type = typ
	// id
	var id uint64
	if idRaw, exists := datas["id"]; exists {
		if idVal, err := util.ToUint64(idRaw); err == nil && idVal > 0 {
			id = idVal
		}
	}
	// code
	code := util.MapKeyValue(datas, "code", "")
	if code != "" {
		// 判断是否存在
		codeExistsQuery := global.MySQL.Model(&model.AdminDepartment{}).Where("`code` = ?", code)
		if id > 0 {
			codeExistsQuery.Where("`id` != ?", id)
		}
		var codeExistsCount int64
		if err = codeExistsQuery.Count(&codeExistsCount).Error; err != nil {
			return fmt.Errorf("数据查询异常！%v", err)
		}
		if codeExistsCount > 0 {
			return fmt.Errorf("部门标识【%s】已存在！", code)
		}
		dbDepartment.Code = code
	}
	if id > 0 {
		// 编辑
		dbDepartment.Id = id
	} else {
		// 新增
		dbDepartment.CreatedAt = &currTime
		dbDepartment.State = stateenum.NORMAL
	}
	datas["dbDepartment"] = dbDepartment
	return
}
